<!--配送商端--退货单管理--质检退回订单--收、退货 -->
<template>
  <div class="beforeSettle-component-box">
    <section>
      <div class="section-header">
        <h3>退货单信息</h3>
      </div>
      <el-row class="detail-base-info">
        <el-col
          :span="8"
          v-for="item in takeBaseInfo"
          :key="item.key">
          <span>{{ item.title }}</span>
          <span v-if="item.key === 'resone'">质检不合格退货</span>
          <span v-else-if="item.key === 'province'">
            {{ baseInfo['province'] }} - {{ baseInfo['city'] }} -
            {{ baseInfo['area'] }} - {{ baseInfo['detailedAddress'] }}
          </span>
          <span v-else-if="item.key === 'orderStatus'">{{
            baseInfo[item.key] === 1 ? '待收货' : '已完成'
          }}</span>
          <span v-else> {{ baseInfo[item.key] }} </span>
        </el-col>
      </el-row>
    </section>
    <section v-if="showDetailTable">
      <div class="section-header">
        <h3>退货明细</h3>
      </div>
      <el-editable
        height="280"
        v-loading="tableLoading"
        :data="detailTableData"
        :columns="takeDetailColumns"
      />
      <el-pagination
        align="right"
        style="margin: 10px 0;"
        @size-change="sizeChangeDetailTable"
        @current-change="pageChangeDetailTable"
        :current-page="curPageDetailTable"
        :page-sizes="PAGE_NUMBER"
        :page-size="pageSizeDetailTable"
        :layout="PAGINATION_LAYOUT"
        :total="totalDetailTable"
      />
    </section>
    <section>
      <div class="section-header">
        <h3>待{{ computedTakeType }}货信息</h3>
        <div>
          <el-button
            size="small"
            @click="importDetails"
          >导入{{ computedTakeType }}货详情</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="downloadImportTemplate"
          >下载导入模板</el-button
          >
          <el-button
            type="text"
            @click="handleReturnClick()"
          >确认收货</el-button
          >
        </div>
      </div>
      <el-editable
        height="auto"
        @selection-change="handleSelectionChange"
        v-loading="tableLoading"
        :data="awaitHandleTableData"
        :columns="takeAwaitHandleColumns"
      >
        <template
          slot="default-expand"
          slot-scope="scope">
          <el-editable
            height="200"
            v-loading="tableLoading"
            :columns="takeAwaitHandleItemColumns"
            :data="scope.row.ocBsCheckReturnReceiveItemDetailVO"
          />
        </template>
        <template
          slot="default-category"
          slot-scope="{row}">
          {{ classify[row.category] }}
        </template>
        <template
          slot="default-awaitReceiveNum"
          slot-scope="{row}">
          {{ row.sweepCount }}/{{ row.awaitReceiveNum }}
        </template>
      </el-editable>
      <el-pagination
        align="right"
        style="margin: 10px 0;"
        @size-change="sizeChangeAwaitHandleTable"
        @current-change="pageChangeAwaitHandleTable"
        :current-page="curPageAwaitHandleTable"
        :page-sizes="PAGE_NUMBER"
        :page-size="pageSizeAwaitHandleTable"
        :layout="PAGINATION_LAYOUT"
        :total="totalAwaitHandleTable"
      />
    </section>
    <!-- 去收、退货弹窗 -->
    <el-dialog
      width="60%"
      :title="'选择' + computedTakeType + '货产品'"
      :visible.sync="collectDialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div>
        <el-form
          ref="form"
          inline
          :model="handleFormData"
          label-width="80px">
          <el-form-item label="扫描条码">
            <el-input
              v-model="handleFormData.barcode"
              @change="inputFun"
              placeholder="解码信息：此处显示扫码解析出的解码信息"
            />
          </el-form-item>
          <el-button type="success">短码</el-button>
        </el-form>
        <section>
          <div class="section-header">
            <h3>产品信息</h3>
          </div>
          <el-editable
            :data="dialogProductTableData"
            v-loading="dialogProductTableLoading"
            :columns="takeDialogProductTableColumns"
          >
            <template
              slot="default-category"
              slot-scope="{row}">
              {{ classify[row.category] }}
            </template>
            <template
              slot="default-awaitReceiveNum"
              slot-scope="{row}">
              {{ writeNum }}/{{ row.awaitReceiveNum }}
            </template>
          </el-editable>
        </section>
        <section>
          <div class="section-header">
            <div>
              <h3 style="display: inline-block; margin-right: 40px;">
                物品详情
              </h3>
              <el-button
                @click.stop="handleDialogGoodsAdd()"
                type="text"
              >添加</el-button
              >
            </div>
          </div>
        </section>
        <el-editable
          height="200"
          :data="dialogGoodsTableData"
          :columns="takeDialogGoodsTableColumns"
        >
          <template
            slot="default-udi"
            slot-scope="scope">
            <el-input
              v-model="scope.row.udi"
              placeholder="请输入" />
          </template>
          <template
            slot="default-barCode"
            slot-scope="scope">
            <el-input
              v-model="scope.row.barCode"
              placeholder="请输入" />
          </template>
          <template
            slot="default-productBatch"
            slot-scope="scope">
            <el-input
              v-model="scope.row.productBatch"
              placeholder="请输入" />
          </template>
          <template
            slot="default-productDate"
            slot-scope="scope">
            <el-date-picker
              v-model="scope.row.productDate"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择日期"
            />
          </template>
          <template
            slot="default-expDate"
            slot-scope="scope">
            <el-date-picker
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              v-model="scope.row.expDate"
              type="date"
              placeholder="选择日期"
            />
          </template>
          <template
            slot="default-serialNumber"
            slot-scope="scope">
            <el-input
              v-model="scope.row.serialNumber"
              placeholder="请输入" />
          </template>
          <!-- 数量 -->
          <template
            slot="default-num"
            slot-scope="scope">
            <el-input
              @change="numChange(scope.row)"
              v-model.number="scope.row.num"
              placeholder="请输入"
            />
          </template>
          <template
            slot="default-action"
            slot-scope="scope">
            <el-button
              size="small"
              @click.stop="handleDialogGoodsDelete(scope.$index)"
              type="text text-primary"
            >删除</el-button
            >
          </template>
        </el-editable>
      </div>
      <div slot="footer">
        <el-button @click="handleDialogCancel">取 消</el-button>
        <el-button
          type="primary"
          @click="handleDialogSubmit">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getReturnForm,
  getByCheckHospitalReturn,
  getByCheckDeliveryReturn,
  addOcBsCheckReceiveItem,
  addCheckItemDetai,
  getProductList,
  returnList,
  getProductItem,
  submitReturnOrder
} from '@const/orderCenterApi'
import { hasIn } from 'lodash'
import { getByBsAddress } from '@const/hospitalSideApi'
import ElEditable from '@components/el-editable'

import NoScrollLayout from '@/layouts/noScrollLayout'

import SearchForm from '@components/businesscomponents/search'
import { PAGE_NUMBER, PAGINATION_LAYOUT } from '@const/common'
export default {
  components: { ElEditable, SearchForm, NoScrollLayout },
  props: {
    orderId: {
      type: String,
      default: ''
    },
    type: {
      // 退、收类型 1：收 2：退
      type: Number,
      default: 1
    },
    interface: {
      type: String,
      default: ''
    },
    showDetailTable: {
      type: Boolean,
      default: true
    },
    baseInfoDic: {
      type: Array,
      default: () => []
    },
    detailColumns: {
      type: Array,
      default: () => []
    },
    awaitHandleColumns: {
      type: Array,
      default: () => []
    },
    awaitHandleItemColumns: {
      type: Array,
      default: () => []
    },
    dialogProductTableColumns: {
      type: Array,
      default: () => []
    },
    dialogGoodsTableColumns: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    baseInfoDic (val) {
      this.takeBaseInfo = val
    },
    detailColumns (val) {
      this.takeDetailColumns = val
    },
    awaitHandleColumns (val) {
      this.takeAwaitHandleColumns = val
    },
    awaitHandleItemColumns (val) {
      this.takeAwaitHandleItemColumns = val
    },
    dialogProductTableColumns (val) {
      this.takeDialogProductTableColumns = val
    },
    dialogGoodsTableColumns (val) {
      this.takeDialogGoodsTableColumns = val
    }
  },
  data () {
    return {
      // 订单产品id
      productItemId: '',
      takeBaseInfo: this.baseInfoDic,
      // 表格Loading
      tableLoading: false,
      // 待质检表头
      takeAwaitHandleColumns: this.awaitHandleColumns,
      // 待质检商品明细
      takeAwaitHandleItemColumns: this.awaitHandleItemColumns,
      // 待收获表格数据
      awaitHandleTableData: [],
      // 退货明细表头
      takeDetailColumns: this.detailColumns,
      // 退货明细数据
      detailTableData: [],
      // 表单编辑默认值
      baseInfo: {},
      // 手写的数量总和
      writeNum: 0,
      // 产品大类
      classify: {
        0: '未知',
        1: '高值',
        2: '低值',
        3: '试剂',
        4: '设备',
        5: '器械'
      },
      selectData: [], // 选择的去收货的列表
      // 详情ID
      detailsId: this.$route.query.id,
      // 去收、退货表单数据
      handleFormData: {
        barcode: ''
      },
      // 去收、退获弹窗
      collectDialogVisible: false,
      // 订单详情
      dialogProductTableData: [],
      dialogProductTableLoading: false,
      // 订单详情表头
      takeDialogProductTableColumns: this.dialogProductTableColumns,
      // 物品详情列表
      dialogGoodsTableData: [{}],
      // 物品详情表头
      takeDialogGoodsTableColumns: this.dialogGoodsTableColumns,
      // 分页数据
      PAGE_NUMBER, // 页码数组
      PAGINATION_LAYOUT, // 页码功能布局
      totalDetailTable: 0,
      curPageDetailTable: 1,
      pageSizeDetailTable: 20,
      totalAwaitHandleTable: 0,
      curPageAwaitHandleTable: 1,
      pageSizeAwaitHandleTable: 20
    }
  },
  computed: {
    computedTakeType () {
      return Object.is(this.type, 1)
        ? '收'
        : Object.is(this.type, 2)
          ? '退'
          : ''
    }
  },
  mounted () {
    this.getHeadInfo()
    this.getReturnList()
    this.getAwaitProductList()
  },

  methods: {
    // 获取待收货信息列表
    getAwaitProductList () {
      this.$axios({
        method: 'post',
        url: getByCheckDeliveryReturn,
        data: {
          page: this.curPageAwaitHandleTable,
          pageSize: this.pageSizeAwaitHandleTable
        }
      }).then(res => {
        let result = hasIn(res, ['data', 'payload']) ? res.data.payload : []
        this.awaitHandleTableData = result.content || []
        this.totalAwaitHandleTable = result.totalElements
      })
    },

    // 获取退货明细
    getReturnList () {
      this.$axios({
        method: 'post',
        url: getByCheckHospitalReturn,
        data: {
          orderId: this.orderId,
          page: this.curPageDetailTable,
          pageSize: this.pageSizeDetailTable
        }
      }).then(res => {
        let result = hasIn(res, ['data', 'payload']) ? res.data.payload : []
        this.detailTableData = result.content || []
        this.totalDetailTable = result.totalElements
      })
    },

    // 获取头部数据
    getHeadInfo () {
      this.$axios({
        method: 'post',
        url: getReturnForm,
        data: {
          orderId: this.orderId
        }
      }).then(res => {
        let result = hasIn(res, ['data', 'payload']) ? res.data.payload : []
        this.baseInfo = result[0] || []
        if (this.baseInfo && this.baseInfo.receiveAddressId) {
          this.getByBsAddress(this.baseInfo.receiveAddressId)
        }
      })
    },

    // 查询地址详情
    getByBsAddress (id) {
      this.$axios
        .$post(getByBsAddress + `?id=${id}`)
        .then(({ code, payload }) => {
          if (!Object.is(code, '0')) return
          this.baseInfo = { ...this.baseInfo, ...payload }
        })
    },
    // 勾选改变触发
    handleSelectionChange (data) {
      this.dialogProductTableData = data
    },

    // 去收货
    handleCollectGoodsClick () {
      if (this.dialogProductTableData.length === 1) { this.collectDialogVisible = true }
      if (this.dialogProductTableData.length > 1) {
        this.$message({
          type: 'warning',
          message: '只能选择一条去收货'
        })
      }
    },

    // 输入数量改变
    numChange (data) {
      let number = 0
      this.dialogGoodsTableData.forEach(item => {
        number += item.num
      })
      this.writeNum = number
    },

    // 导入收货详情
    importDetails () {
      console.log('导入收、退货详情按钮点击事件')
    },
    // 下载导出模板
    downloadImportTemplate () {
      console.log('下载导入模板按钮点击事件')
    },
    // 添加一行
    handleDialogGoodsAdd () {
      console.log('向收货对话框物品详情添加一行')
      this.dialogGoodsTableData.push({})
    },
    // 删除一行
    handleDialogGoodsDelete (index) {
      console.log('向收货对话框物品详情删除一行')
      this.dialogGoodsTableData.splice(index, 1)
    },
    // 退货提交前验证
    validSubmitReturnOrder () {
      // 校验数据必填情况
      const emptyRow = this.dialogGoodsTableData.find(
        item =>
          !item.udi ||
          !item.barCode ||
          !item.productBatch ||
          !item.productDate ||
          !item.expDate ||
          !item.serialNumber ||
          !item.num
      )
      if (emptyRow) {
        this.$message.error('物品详情存在未填写项')
        return false
      }
      // 计算物品详情中总数量，对比产品信息中退货数量，必须相等才可以退货
      const total = this.dialogGoodsTableData.reduce(
        (total, item) => total + Number(item.num),
        0
      )
      // 获取退货数量
      const returnNum = this.dialogProductTableData[0].returnNum
      if (!Object.is(total, returnNum)) {
        this.$message.error(
          `物品详情中数量总和${total}与退货数量${returnNum}不相等`
        )
        return false
      }
      return true
    },
    // 退货接口调用方法
    fetchSubmitReturnOrder () {
      this.$axios
        .$post(submitReturnOrder, {
          id: this.productItemId,
          detailPOS: this.dialogGoodsTableData
        })
        .then(({ code }) => {
          if (!Object.is(code, '0')) return
          this.$message.success('退货成功')
          this.handleDialogCancel()
          this.initPage()
        })
    },
    // 提交退货逻辑
    async submitReturnOrder () {
      const valid = await this.validSubmitReturnOrder()
      valid && this.fetchSubmitReturnOrder()
    },
    resetDialog () {
      this.dialogProductTableData = []
      this.dialogGoodsTableData = [{}]
    },
    // 去收、退货弹窗提交
    handleDialogSubmit () {
      if (this.writeNum > this.dialogProductTableData[0].awaitReceiveNum) {
        this.$message({
          type: 'error',
          message: '已扫码数量不能大于待收数量'
        })
      } else {
        let data = this.dialogGoodsTableData.map(item => {
          return { ...item, id: this.dialogProductTableData[0].id }
        })
        this.$axios({
          method: 'post',
          url: addCheckItemDetai,
          data: data
        }).then(res => {
          this.$message({
            type: 'success',
            message: '扫码成功'
          })
          this.getAwaitProductList()
          this.collectDialogVisible = false
        })
      }
    },
    // 去收、退获弹窗取消
    handleDialogCancel () {
      this.resetDialog()
      this.collectDialogVisible = false
    },
    // 扫码的内容
    inputFun (val) {},
    // 确认收货
    handleReturnClick () {
      this.$axios({
        method: 'post',
        url: addOcBsCheckReceiveItem,
        data: {
          id: this.$route.query.orderId
        }
      }).then(res => {
        this.$message({
          type: 'success',
          message: '收货成功'
        })
        this.$router.push({
          path: '/distributorSide/returnOrderManage/qualityReturn'
        })
      })
    },
    // 页码、页数变更事件
    sizeChangeDetailTable (size) {
      this.pageSizeDetailTable = size
      this.getReturnList()
    },
    pageChangeDetailTable (page) {
      this.curPageDetailTable = page
      this.getReturnList()
    },
    sizeChangeAwaitHandleTable (size) {
      this.pageSizeAwaitHandleTable = size
      this.getAwaitProductList()
    },
    pageChangeAwaitHandleTable (page) {
      this.curPageAwaitHandleTable = page
      this.getAwaitProductList()
    }
  }
}
</script>

<style lang="less" scope>
.beforeSettle-component-box {
  section {
    .section-header {
      display: flex;
      padding-bottom: 12px;
      margin-bottom: 16px;
      padding-right: 16px;
      justify-content: space-between;
      border-bottom: 1px solid rgba(238, 240, 245, 1);
    }

    h3 {
      font-size: 16px;
      font-weight: 500;
      line-height: 22px;
      color: rgba(38, 52, 76, 1);
    }

    .detail-base-info {
      .el-col {
        margin-bottom: 10px;
        height: 20px;
        line-height: 20px;

        > span {
          width: 49%;
          font-weight: 400;
          line-height: 20px;
          display: inline-block;

          &:first-child {
            text-align: right;
            padding-right: 8px;
            color: rgba(167, 177, 199, 1);
          }

          &:last-child {
            overflow: hidden;
            white-space: nowrap;
            vertical-align: bottom;
            text-overflow: ellipsis;
            color: rgba(38, 52, 76, 1);
          }
        }
      }
    }
  }
}
</style>
